import sys

# 直接复用Pipeline实例
sys.path.append("./")
pipeline = __import__("05-table-question-answering")

import gradio as gr


# 定义表格问答函数
def answer_table_question(query, table):
    # 将字符串形式的表格转换为列表字典
    table_list = [dict(zip(table.split('\n')[0].split(','), row.split(','))) for row in table.split('\n')[1:]]
    result = pipeline.nlp(query=query, table=table_list)
    return f"答案: {result['answer']}"


# 创建Gradio界面
with gr.Blocks() as demo:
    gr.Markdown("# 表格问答系统")
    gr.Markdown(
        "这是一个基于Transformers框架的表格问答工具。您可以输入一个问题和一段CSV格式的表格文本，点击“提交”按钮后，系统将尝试从中找到答案。")

    with gr.Row():
        input_table = gr.Textbox(placeholder="请输入表格数据（CSV格式）...", label="表格")

    with gr.Row():
        input_query = gr.Textbox(placeholder="请输入您的问题...", label="问题")

    with gr.Row():
        submit_button = gr.Button("提交")

    with gr.Row():
        output_answer = gr.Label(label="答案")

    # 设置按钮点击事件，触发表格问答函数
    submit_button.click(answer_table_question, inputs=[input_query, input_table], outputs=output_answer)

# 启动Gradio应用
if __name__ == "__main__":
    demo.launch()
